package com.dfhz.ken.zermall.UI.activity.shopins;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dfhz.ken.zermall.R;
import com.dfhz.ken.zermall.UI.activity.LocalImageActivity;
import com.dfhz.ken.zermall.UI.base.BaseActivity;
import com.dfhz.ken.zermall.entity.postbean.Shopin;
import com.dfhz.ken.zermall.utils.Base64Coder;
import com.dfhz.ken.zermall.utils.DownImageUtils;
import com.dfhz.ken.zermall.utils.L;
import com.dfhz.ken.zermall.utils.MyViewHolder;
import com.dfhz.ken.zermall.utils.SaveImage;
import com.dfhz.ken.zermall.utils.SetImage;
import com.dfhz.ken.zermall.utils.StringUtil;
import com.dfhz.ken.zermall.utils.TAkePhotos;
import com.dfhz.ken.zermall.utils.ToastUtil;
import com.dfhz.ken.zermall.utils.network.NetWorkUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import widget.customview.toolbar.ExpendedGridView;

/**
 * Created by huangyuekai on 16/11/24.
 */
public class FabuShopinActivity2 extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.rel_title)
    RelativeLayout relTitle;
    @Bind(R.id.edt_describe)
    EditText edtDescribe;
    @Bind(R.id.tvt_address)
    TextView tvtAddress;
    @Bind(R.id.rel_add_address)
    RelativeLayout relAddAddress;
    @Bind(R.id.rb_tejia)
    RadioButton rbTejia;
    @Bind(R.id.rb_dazhe)
    RadioButton rbDazhe;
    @Bind(R.id.rb_manjian)
    RadioButton rbManjian;
    @Bind(R.id.radio_group)
    RadioGroup radioGroup;
    @Bind(R.id.price_type_tejia)
    TextView priceTypeTejia;
    @Bind(R.id.price_type_dazhe)
    TextView priceTypeDazhe;
    @Bind(R.id.price_type_manjian)
    TextView priceTypeManjian;
    @Bind(R.id.edt_tejia_all_price)
    EditText edtTejiaAllPrice;
    @Bind(R.id.lin_tejia)
    LinearLayout linTejia;
    @Bind(R.id.edt_dazhe_zhekou)
    EditText edtDazheZhekou;
    @Bind(R.id.lin_dazhe)
    LinearLayout linDazhe;
    @Bind(R.id.edt_man_all)
    EditText edtManAll;
    @Bind(R.id.edt_man_jian)
    EditText edtManJian;
    @Bind(R.id.lin_manjian)
    LinearLayout linManjian;
    @Bind(R.id.tvt_start_time)
    TextView tvtStartTime;
    @Bind(R.id.tvt_end_time)
    TextView tvtEndTime;
    @Bind(R.id.tvt_leibie)
    TextView tvtLeibie;
    @Bind(R.id.lin_leibie)
    LinearLayout linLeibie;
    @Bind(R.id.tvt_pinpai)
    TextView tvtPinpai;
    @Bind(R.id.lin_pinpai)
    LinearLayout linPinpai;
    @Bind(R.id.btn_commit)
    TextView btnCommit;
    @Bind(R.id.recommendGridView)
    ExpendedGridView reImgGridView;

    private static int TYPE_TEJIA = 0;
    private static int TYPE_DAZHE = 1;
    private static int TYPE_MANJIAN = 2;
    private int priceType = TYPE_DAZHE;

    private ImageView imageview;
    public static Uri photoUri;// 照相之后的数据
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private String image1 = ""; // 存储图片字符串

    public static final int REQUEST_PICTURE_CODE = 1001;
    private static final String FRIEND_CIRCLE_ADD_PICTURE = "friend_circle_and_picture";
    public static final int PHOTO_REQUEST_CAMERA5 = 1005;// 拍照
    private int imagelistsize = 0;//图片列表长度
    private ArrayList<String> pathModel;//用于接收上个界面的图片列表
    private ArrayList<String> sendtoserverimagelist;
    private ImagesAdapter imagesAdapter;

    @Override
    protected void setMainLayout() {
        setContentView(R.layout.activity_shopin_fabu);
        ButterKnife.bind(this);
    }

    @Override
    protected void initBeforeData() {
        pathModel = new ArrayList<String>();
        sendtoserverimagelist = new ArrayList<String>();

        if (null != pathModel && null != pathModel) {
            imagelistsize = pathModel.size();
        } else {
            imagelistsize = 0;
        }

        if (pathModel != null && pathModel.size() < 8) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }

        imagesAdapter = new ImagesAdapter(pathModel);
        reImgGridView.setAdapter(imagesAdapter);
    }

    @Override
    protected void initEvents() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setCheckUI();
                switch (checkedId) {
                    case R.id.rb_tejia:
                        priceTypeTejia.setTextColor(getResources().getColor(R.color.red));
                        linTejia.setVisibility(View.VISIBLE);
                        priceType = TYPE_TEJIA;
                        break;
                    case R.id.rb_dazhe:
                        priceTypeDazhe.setTextColor(getResources().getColor(R.color.red));
                        linDazhe.setVisibility(View.VISIBLE);
                        priceType = TYPE_DAZHE;
                        break;
                    case R.id.rb_manjian:
                        priceTypeManjian.setTextColor(getResources().getColor(R.color.red));
                        linManjian.setVisibility(View.VISIBLE);
                        priceType = TYPE_MANJIAN;
                        break;
                }
            }
        });
    }

    @Override
    protected void initAfterData() {

    }

    @Override
    public void back(View view) {

    }

    private void setCheckUI() {
        linTejia.setVisibility(View.GONE);
        linDazhe.setVisibility(View.GONE);
        linManjian.setVisibility(View.GONE);
        priceTypeTejia.setTextColor(getResources().getColor(R.color.black));
        priceTypeDazhe.setTextColor(getResources().getColor(R.color.black));
        priceTypeManjian.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_commit:

                if (condition())
                    setBean();
                break;
        }
    }

    /**
     * 信息校验
     *
     * @return
     */
    private boolean condition() {
        if (sendtoserverimagelist.size() < 0) {
            ToastUtil.show(FabuShopinActivity2.this, "你还没有上传至照片");
            return false;
        }
        return true;
    }


    /**
     * 设置上传前的数据
     */
    private void setBean() {
        Shopin bean = new Shopin();
        bean.setOne(getImageToView(sendtoserverimagelist.get(0)));
        if (sendtoserverimagelist.size() == 2)
            bean.setTwo(getImageToView(sendtoserverimagelist.get(1)));
        if(sendtoserverimagelist.size() == 3)
            bean.setThree(getImageToView(sendtoserverimagelist.get(2)));
        bean.setDescribe(edtDescribe.getText().toString());
        bean.setAddress("苏州无电源");
        if(priceType == TYPE_TEJIA){
            bean.setDiscountInfo("");
            bean.setDiscountType("特价");
        }else if(priceType == TYPE_DAZHE){
            bean.setDiscountInfo("");
            bean.setDiscountType("打折");
        }else{
            bean.setDiscountInfo("");
            bean.setDiscountType("满减");
        }
        bean.setBeginTime(tvtStartTime.getText().toString());
        bean.setEndTime(tvtEndTime.getText().toString());
        bean.setTypeId("1");
        bean.setBrandId("1");
        fabuShopin(bean);
    }

    /**
     * 发布上传
     * @param shopin
     */
    private void fabuShopin(Shopin shopin){
        NetWorkUtil.addShopin(shopin, "0", new NetWorkUtil.ICallBack() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure() {

            }

            @Override
            public void onException() {

            }
        });

    }

    /**
     * 将图片转换成字节流以待上传。。。
     *
     * @param,picdata
     */
    private String getImageToView(String path) {
        final String cutpath = path.substring(7, path.length());
        Bitmap photo = new SaveImage().compressedBitmap(cutpath);
        // 上传头像到服务器上去
        // bitmap 转换 String
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
        byte[] b = stream.toByteArray();
        // 将图片流以字符串形式存储下来
        L.e("图片被转换成了字符流",new String(Base64Coder.encodeLines(b)));
        return new String(Base64Coder.encodeLines(b));
        // uploadImage(imageStrData);

    }

    private Dialog dialog;

    public void showbgdialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_select_image, null);
        TextView takephoto = (TextView) view.findViewById(R.id.tv_teke_picture);
        TextView select = (TextView) view.findViewById(R.id.tv_select_photo);
        TextView no = (TextView) view.findViewById(R.id.tv_sendContentDialogFragment_cancel);

        final AlertDialog.Builder builder =
                new AlertDialog.Builder(FabuShopinActivity2.this, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
        dialog.setCanceledOnTouchOutside(true);

        takephoto.setAlpha(0.85f);
        select.setAlpha(0.85f);
        no.setAlpha(0.85f);

        dialog.show();

//        WindowManager windowManager = context.getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
//        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//        lp.width = (int) (display.getWidth()); //设置宽度
        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) ((dm.widthPixels) / 1.05);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);

        //拍照
        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TAkePhotos(FabuShopinActivity2.this).cameraphoto(PHOTO_REQUEST_CAMERA5);
                dialog.dismiss();
            }
        });
        //相册
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent localPicture = new Intent(FabuShopinActivity2.this, LocalImageActivity.class);
                localPicture.putExtra("listsize", imagelistsize);
                startActivityForResult(localPicture, REQUEST_PICTURE_CODE);
                dialog.dismiss();
            }
        });
        //取消
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private Uri sCurrentUri;//拍照时用于存放图片Uri

    public void setUri(Uri uri) {
        sCurrentUri = uri;
        L.e("setUri=", uri + "");
        L.e("setUri转换后的path=", SaveImage.getRealFilePath(FabuShopinActivity2.this, uri));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //拍照
                case PHOTO_REQUEST_CAMERA5:
                    if (hasSdcard()) {
                        Log.e("拍照相片路径", sCurrentUri + "");

                        if (data == null) {
                            String path = sCurrentUri + "";

                            final String cutpath = path.substring(7, path.length());
                            String afterpath = new SaveImage().compressed(cutpath);

                            if (afterpath != null) {
                                Log.e("", afterpath);
                                //先将带“添加符号”的图片删除，然后添加拍照的图片，
                                //最后判断总长度是否为3，若为3，就不操作，否则，添加带“添加符号”的图片

                                for (String s : pathModel) {
                                    if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                        pathModel.remove(s);
                                        break;
                                    }
                                }
                                pathModel.add("file://" + afterpath);
                                if (pathModel.size() < 3) {
                                    pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }

                                sendtoserverimagelist.add("file://" + afterpath);//用于存放上传服务器的图片列表

                                imagelistsize++;//用于显示的图片列表长度加1

                                imagesAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        Toast.makeText(FabuShopinActivity2.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                    break;

                //选择照片
                case REQUEST_PICTURE_CODE:
                    requestPicture(data);
                    break;
            }
        }
    }

    /**
     * 获取图片
     *
     * @param data Intent
     */
    private void requestPicture(Intent data) {
        pathModel.remove(FRIEND_CIRCLE_ADD_PICTURE);
        if (data != null) {
            pathModel.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));


            imagelistsize = imagelistsize + (data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS)).size();

            //用于存放上传服务器的图片列表
            sendtoserverimagelist.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));

        }
        if (pathModel.size() < 3) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }

        for (String uri : pathModel) {
            L.e("图片Uri地址", uri);
        }


        imagesAdapter.notifyDataSetChanged();
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Message gridView的适配器
     *
     * @param
     * @param
     * @return
     */

    private class ImagesAdapter extends ArrayAdapter<String> {

        private List<String> list;

        public ImagesAdapter(List<String> list) {
            super(FabuShopinActivity2.this, 0, list);
            this.list = list;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_item_image, null);
            }

            ImageView delete = MyViewHolder.get(convertView, R.id.delete);
            ImageView imageView = MyViewHolder.get(convertView, R.id.image_show);
            TextView text = MyViewHolder.get(convertView, R.id.image_text);
            final String uri = getItem(position);

            //根据是否是“添加图片”显示布局

            if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
               /* ImageLoader.getInstance().init(DownImageUtils.configImage(FabuShopinActivity2.this));
                ImageLoader.getInstance().displayImage("drawable://" + R.drawable.btn_add_photo, imageView);
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);*/
                imageView.setImageResource(R.drawable.btn_add_photo);
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                delete.setVisibility(View.GONE);
                text.setVisibility(View.GONE);
            } else {
                //ImageLoader.getInstance().displayImage(getItem(position), imageView);
                SetImage.setimage(FabuShopinActivity2.this, getItem(position), imageView);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                delete.setVisibility(View.VISIBLE);
                text.setVisibility(View.VISIBLE);
                if (position == 0) {
                    text.setText("剖面结构图");
                }
                if (position == 1) {
                    text.setText("样品图");
                }
                if (position == 2) {
                    text.setText("应用实景图1");
                }
                if (position > 2) {
                    text.setText("");
                }
            }

            //删除时判断list长度是否小于3，若小于 则直接删除，不用添加“添加符号的图片” ，
            // 否则，先删除选中图片，然后判断原来有没有那张“添加图片”，若有 那就不操作，若无，就添加“添加图片”
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //删除来自网络图片（编辑状态）

//                    if (netImages != null && netImages.images.size() > 0) {
//                        for (ProductsAndMaterial.Photo s : netImages.images) {
//                            if ((RequestMapDev.BASE_URL.substring(0, RequestMapDev.BASE_URL.length() - 1) + s.url).equals(list.get(position))) {
//                                //FinalHttpWu.deletephoto(ReleaseActivity.this, s.id);
//                                netImages.images.remove(s);
//                                isbianji = true;//此时已经修改过进入界面的信息，（用于退出时判断是否弹dialog）
//                                break;
//                            }
//                        }
//                    }


                    //删除用于上传服务器的图片

                    for (String s : sendtoserverimagelist) {
                        if (s.equals(list.get(position))) {
                            sendtoserverimagelist.remove(s);
                            break;
                        }
                    }


                    if (list.size() < 3) {
                        list.remove(position);

                    } else {
                        list.remove(position);
                        int i = 0;
                        for (String s : list) {
                            if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                break;
                            } else {
                                i++;
                                if (i == list.size()) {
                                    list.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }
                            }
                        }
                    }
                    imagelistsize--;//用于显示的列表长度减1

                    imagesAdapter.notifyDataSetChanged();
                }
            });

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
                        showbgdialog();
                    } else {
                        //查看大图
                    }
                }
            });

            return convertView;
        }
    }
}
